﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WHC.Hotel.Entity;
using WHC.Hotel.BLL;

using WHC.Hotel.UI.Controls;
using WHC.OrderWater.Commons;

namespace WHC.Hotel.UI
{
    public partial class FrmProtocolUnitEndit : BaseForm
    {
        private WinFormCallBackHelp mWinFormCallBackHelp = null;
        private string mainKey = string.Empty;
        public FrmProtocolUnitEndit()
        {
            InitializeComponent();
        }

        public FrmProtocolUnitEndit(WinFormCallBackHelp winFormCallBackHelp)
        {
            InitializeComponent();
            mWinFormCallBackHelp = winFormCallBackHelp;
        }

        private void FrmProtocolUnitEndit_Load(object sender, EventArgs e)
        {
            InitUnitType();
            if (mWinFormCallBackHelp.Action == "edit")
            {

                DisplayData();
            
            
            }

            ShowDiscountInfo();
           // dgRoom.Columns["RoomDiscountPrice"].ReadOnly = false;

        }


        /// <summary>
        /// 实现控件输入检查的函数
        /// </summary>
        /// <returns></returns>
        public  bool CheckInput()
        {
            bool result = true;//默认是可以通过

            #region MyRegion
            if (this.txtUnitCode.Text.Trim().Length == 0)
            {
            
                MessageUtil.ShowTips("请输入协议号");
                this.txtUnitCode.Focus();
                result = false;
            }
            else if (this.txtUnitName.Text.Trim().Length == 0)
            {
                MessageUtil.ShowTips("请输入协议单位");
                this.txtUnitName.Focus();
                result = false;
            }

            else if (this.cmbUnitType.Text.Trim().Length == 0)
            {
                MessageUtil.ShowTips("请选择协议类别");
                this.cmbUnitType.Focus();
                result = false;
            }
            else if (this.txtContactUser.Text.Trim().Length == 0)
            {
                MessageUtil.ShowTips("请输入联系人");
                this.txtContactUser.Focus();
                result = false;
            }
            else if (this.txtContactPhone.Text.Trim().Length == 0)
            {
                MessageUtil.ShowTips("请输入联系电话");
                this.txtContactPhone.Focus();
                result = false;
            }
            else if (this.txtUserName.Text.Trim().Length == 0)
            {
                MessageUtil.ShowTips("请输入销售员");
                this.txtUserName.Focus();
                result = false;
            }

            else if (chkAllowHang.Checked && this.txtHangMaxAmount.Text.Trim().Length == 0)
            {
                MessageUtil.ShowTips("请输入挂账限额");
                this.txtHangMaxAmount.Focus();
                result = false;
            }
     
            #endregion

            return result;
        }

        /// <summary>
        /// 数据显示的函数
        /// </summary>
        public  void DisplayData()
        {
           
            if (!string.IsNullOrEmpty(mWinFormCallBackHelp.MainKey))
            {
                #region 显示客户信息
                ProtocolUnitInfo info = BLLFactory<ProtocolUnit>.Instance.FindByID(mWinFormCallBackHelp.MainKey);
                if (info != null)
                {
                  
                    txtUnitName.Text = info.UnitName;
                    txtUnitCode.Text = info.UnitCode;
                    cmbUnitType.Text = info.UnitType;
                    txtUserName.Text = info.UserName;
                    chkAllowHang.Checked = info.IsAllowHang;
                    txtHangMaxAmount.Text = info.HangMaxAmount.ToString("f2");
                    txtAddress.Text = info.Address;
                    txtRemark.Text = info.Remark;
                    txtContactUser.Text = info.ContactUser;
                    txtContactPhone.Text = info.ContactPhone;
                }
                #endregion
                //this.btnOK.Enabled = Portal.gc.HasFunction("ProtocolUnit/Edit");             
            }
            else
            {
                //this.btnOK.Enabled = Portal.gc.HasFunction("ProtocolUnit/Add");  
            }
        }

        private void InitUnitType()
        {

            this.cmbUnitType.Items.Clear();
            this.cmbUnitType.Items.AddRange(DictItemUtil.GetProtocolUnitType());
            if (this.cmbUnitType.Items.Count > 0)
            {
                this.cmbUnitType.SelectedIndex = 0;
            }
        }


        /// <summary>
        /// 显示房间信息
        /// </summary>
        private void ShowDiscountInfo()
        {
            DataTable dt = null;
            this.dgRoom.AutoGenerateColumns = false;
            if (mWinFormCallBackHelp.Action == "add")
            {
                dt = BLLFactory<RoomType>.Instance.GetAllToDataTable();
                this.dgRoom.Columns["Id"].DataPropertyName = "Id";
                this.dgRoom.Columns["RoomType"].DataPropertyName = "Name";
                this.dgRoom.Columns["RoomPrice"].DataPropertyName = "DayPrice";
               // this.dgRoom.Columns["RoomDiscountPrice"].DataPropertyName = "DayPrice";

            }
            else
            {

                dt = BLLFactory<DiscountInfo>.Instance.FindToDataTable("   RelativeId=" + mWinFormCallBackHelp.MainKey);
                this.dgRoom.Columns["Id"].DataPropertyName = "Id";
                this.dgRoom.Columns["RoomType"].DataPropertyName = "RoomType";
                this.dgRoom.Columns["RoomPrice"].DataPropertyName = "RoomPrice";
                this.dgRoom.Columns["RoomDiscountPrice"].DataPropertyName = "RoomDiscountPrice";
            
            
            }

            this.dgRoom.DataSource = dt;




        }

        /// <summary>
        /// 编辑或者保存状态下取值函数
        /// </summary>
        /// <param name="info"></param>
        private void SetInfo(ProtocolUnitInfo info)
        {
            info.UnitName = txtUnitName.Text;
            info.UnitCode = txtUnitCode.Text;
            info.UnitType = cmbUnitType.Text;
            info.UserName = txtUserName.Text;
            info.UserId = 0; ;
            info.IsAllowHang = chkAllowHang.Checked;
            if (string.IsNullOrEmpty(txtHangMaxAmount.Text))
            {
                info.HangMaxAmount = 0;

            }
            else
            {

                info.HangMaxAmount = Convert.ToDecimal(txtHangMaxAmount.Text);
            
            }
            info.Address = txtAddress.Text;
            info.Remark = txtRemark.Text;
            info.ContactUser = txtContactUser.Text;
            info.ContactPhone = txtContactPhone.Text;
           
        }

        /// <summary>
        /// 新增状态下的数据保存
        /// </summary>
        /// <returns></returns>
        public  bool SaveAddNew()
        {
            ProtocolUnitInfo info = new ProtocolUnitInfo();
            info.OperatorUser = Portal.gc.LoginInfo.FullName;
            SetInfo(info);
            List<DiscountInfoInfo> list=new List<DiscountInfoInfo>();
            GetRoomTypeDiscount(list);

            try
            {
                #region 新增数据

                bool succeed = BLLFactory<ProtocolUnit>.Instance.Insert(info);
                if (succeed)
                {
                    ProtocolUnitInfo mProtocolUnitInfo = BLLFactory<ProtocolUnit>.Instance.FindSingle("   UnitName='" + txtUnitName.Text + "'");
                    foreach (DiscountInfoInfo entity in list)
                    {
                      
                       if (mProtocolUnitInfo != null)
                       {

                           entity.RelativeId = mProtocolUnitInfo.Id;
                           BLLFactory<DiscountInfo>.Instance.Insert(entity);

                       }
                    
                    
                    }
                    //可添加其他关联操作

                    return true;
                }
                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                MessageUtil.ShowError(ex.Message);
            }
            return false;
        }

        /// <summary>
        /// 编辑状态下的数据保存
        /// </summary>
        /// <returns></returns>
        public  bool SaveUpdated()
        {

            ProtocolUnitInfo info = BLLFactory<ProtocolUnit>.Instance.FindByID(mWinFormCallBackHelp.MainKey);
            if (info != null)
            {
                SetInfo(info);
                List<DiscountInfoInfo> list = new List<DiscountInfoInfo>();
                GetRoomTypeDiscount(list);
                
                try
                {
                    #region 更新数据
                    bool succeed = BLLFactory<ProtocolUnit>.Instance.Update(info, info.Id.ToString());
                    if (succeed)
                    {
                        //可添加其他关联操作
                        foreach (DiscountInfoInfo entity in list)
                        {

                            BLLFactory<DiscountInfo>.Instance.Update(entity,entity.Id.ToString());


                        }
                        return true;
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError(ex.Message);
                }
            }
            return false;
        }

        private void GetRoomTypeDiscount(List<DiscountInfoInfo> list)
        {
          
            foreach (DataGridViewRow row in this.dgRoom.Rows)
            {

                DiscountInfoInfo entity = new DiscountInfoInfo();
          
                entity.RoomType = row.Cells["RoomType"].Value.ToString();
                entity.UnitName = txtUnitName.Text;
                entity.RoomTypeId = 0;
                entity.RoomPrice = Convert.ToDecimal(row.Cells["RoomPrice"].Value.ToString());
                if (mWinFormCallBackHelp.Action == "edit")
                {
                    entity.Id = Convert.ToInt32(row.Cells["Id"].Value.ToString());
                    entity.RelativeId = Convert.ToInt32(mWinFormCallBackHelp.MainKey);

                }
                else
                {
                    entity.Id = 0;
                    entity.RelativeId = 0;
                
                }
                if (string.IsNullOrEmpty(row.Cells["RoomDiscountPrice"].Value.ToString()))
                {
                    entity.RoomDiscountPrice = entity.RoomPrice;
                }
                else
                {
                    entity.RoomDiscountPrice = Convert.ToDecimal(row.Cells["RoomDiscountPrice"].Value.ToString());

                }

                entity.DiscountPercent = entity.RoomDiscountPrice / entity.RoomPrice; 
                list.Add(entity);



            }
        
        
        
        
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (CheckInput())
            {

                if (mWinFormCallBackHelp.Action == "edit")
                {

                    if (SaveUpdated())
                    {

                        mWinFormCallBackHelp.ReFlashParentWindow();
                        MessageUtil.ShowTips("保存成功");

                    }
                    else
                    {

                        MessageUtil.ShowTips("保存失败");
                    
                    }

                }
                else
                {


                    if (SaveAddNew())
                    {

                        if (!chkNotClose.Checked)
                        {

                            this.Close();
                        
                        }

                        mWinFormCallBackHelp.ReFlashParentWindow();
                        MessageUtil.ShowTips("保存成功");

                    }
                    else
                    {

                        MessageUtil.ShowTips("保存失败");

                    }

                }

            }



        }

        private void btnCanel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgRoom_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {

            if (mWinFormCallBackHelp.Action == "add")
            {
                foreach (DataGridViewRow row in this.dgRoom.Rows)
                {

                    row.Cells["RoomDiscountPrice"].Value = row.Cells["RoomPrice"].Value;

                }
            
            }

        }

      
      
    }
}
